package asmilk.astest.service.impl;

import static java.util.concurrent.TimeUnit.MILLISECONDS;

import java.io.IOException;
import java.net.CookieManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import asmilk.astest.service.WeiboService;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.JavaNetCookieJar;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

@Service
public class WeiboServiceImpl implements WeiboService {

	private static final Logger LOG = LoggerFactory.getLogger(WeiboServiceImpl.class);

	private static final String APP_KEY = "2041355429";
	private static final String APP_SECRET = "4e5fd8b90d89108d30c51c7ac8223ef8";
	private static final String GRANT_TYPE = "authorization_code";
	private static final String REDIRECT_URL = "http://astest.butterfly.mopaasapp.com/authorize";

	private static OkHttpClient client;

	static {
		client = new OkHttpClient.Builder().connectTimeout(0, MILLISECONDS).readTimeout(0, MILLISECONDS)
				.writeTimeout(0, MILLISECONDS).cookieJar(new JavaNetCookieJar(new CookieManager())).build();
	}

	@Override
	public String accessToken(String code) {
		LOG.info("!!!accessToken():begin!!!");
		
		String content = null;
		
		HttpUrl url = HttpUrl.parse("https://api.weibo.com/oauth2/access_token");
		LOG.info("url: {}", url);

		FormBody body = new FormBody.Builder().add("client_id", APP_KEY).add("client_secret", APP_SECRET)
				.add("grant_type", GRANT_TYPE).add("redirect_uri", REDIRECT_URL).add("code", code).build();
		Request request = new Request.Builder().url(url).post(body).build();
		try {
			Response response = client.newCall(request).execute();
			content = response.body().string();
			LOG.info("content:{}", content);
		} catch (IOException e) {
			LOG.error(e.getMessage(), e);
		} finally {
			LOG.info("!!!accessToken():end!!!");
		}
		return content;
	}

}
